package ai;

import game.Game;

public class Randomiser extends Ai {
	
	// variables for calculating with a generated random number
	private static final int A =  48271;
	private static final int M = 2147483647; // 2^31 -1 prime number
	private static final int Q = M / A;
	private static final int R = M % A;
	private int state;
	
	//generate integer together with current time in milliseconds
	public Randomiser(Game game, byte side)
	{
		super(game, side);
		int initialValue = ( (int) System.currentTimeMillis() % Integer.MAX_VALUE );
		
		if ( initialValue < 0 )
		{
			initialValue += M;
		}
		
		state = initialValue;
		if ( state == 0 )
		{
			state = 1;
		}
	}
	
	// generate the next move
	protected int getZet()
	{
		int temp;
		
		synchronized(this.game)
		{
			do {
				temp = nextInt() % Game.XSIZE;
			} while (this.columnIsFull(temp, this.game));
		}
		
		return temp;
	}
	
	
	// generates a new integer based on the previous used integer
	public int nextInt()
	{
		int tmpState = A * ( state % Q ) - R * ( state / Q );
		if ( tmpState >= 0 )
		{
			state = tmpState;
		}
		else
			state = tmpState + M;
		return state;
	}
	
	//A function that checks if a column is full
	protected boolean columnIsFull(int column, Game game)
	{
		return (this.game.getPlayingField()[column][0] != Game.EMPTY);
	}
	
}
